package com.jjsj.quartz.sf.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jjsj.common.utils.DateUtils;
import com.jjsj.common.utils.spring.SpringUtils;
import com.jjsj.mall.entity.OrderInfo;
import com.jjsj.mall.entity.OrderLogistics;
import com.jjsj.mall.entity.OrderLogisticsExpressInfo;
import com.jjsj.mall.service.OrderInfoService;
import com.jjsj.mall.service.OrderLogisticsExpressInfoService;
import com.jjsj.mall.service.OrderLogisticsService;
import com.jjsj.quartz.sf.model.*;
import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.csim.express.service.HttpClientUtil;
import com.sf.csim.express.service.IServiceCodeStandard;
import com.sf.csim.express.service.code.ExpressServiceCodeEnum;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Pattern;

public class SFExpressNewAPIService {

    OrderInfoService orderInfoService = (OrderInfoService) SpringUtils.getBean("OrderInfoService");

    OrderLogisticsService orderLogisticsService = (OrderLogisticsService) SpringUtils.getBean("OrderLogisticsService");

    OrderLogisticsExpressInfoService orderLogisticsExpressInfoService = (OrderLogisticsExpressInfoService) SpringUtils.getBean("OrderLogisticsExpressInfoService");

    /**
     * 丰桥新沙箱测试顾客编码  Yg4Zf06w_sxZs3A5D
     * 校验码  3Xdk1jqeG1Xod9nUXus8Op7DNOkchTnw
     **/
    private static final String CLIENT_CODE = "JYJSS240HEk0";  //此处替换为您在丰桥平台获取的顾客编码
    private static final String CHECK_WORD_BOX = "dGlsr1y6Q5jnhj6DpVnd4QrHbIyRPcHS";//此处替换为您在丰桥平台获取的校验码
    private static final String CHECK_WORD_PROD = "ZU9woL1SggxxHsKFBm9ujcBXiKORXAvh";//此处替换为您在丰桥平台获取的校验码


    //沙箱环境的地址 -PRO
    private static final String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";
    //生产环境的地址 -PRO
    private static final String CALL_URL_PROD = "https://sfapi.sf-express.com/std/service";

    public void sfRout() throws UnsupportedEncodingException {
        /**ExpressServiceCodeEnum     对应速运类-快递APIs
         POSTServiceCodeEnum        对应速运类-驿站APIs
         YJTServiceCodeEnum         对应解决方案-医寄通APIs
         EPSServiceCodeEnum         对应解决方案-快递管家APIs
         HZTServiceCodeEnum         对应解决方案-函证通APIs    2022-2-24 新增
         详情见code目录下枚举类，客户可自行修改引用的该类
         **/

//        IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_CREATE_ORDER; //下订单
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_SEARCH_ORDER_RESP; //查订单
        //  IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_UPDATE_ORDER;//订单取消
        // 	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_FILTER_ORDER_BSP;//订单筛选
        IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_SEARCH_ROUTES;//查路由
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_GET_SUB_MAILNO;//子单号
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_QUERY_SFWAYBILL;//查运费
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_REGISTER_ROUTE;//注册路由
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_CREATE_REVERSE_ORDER;//退货下单
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_CANCEL_REVERSE_ORDER;//退货消单
        //	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_WANTED_INTERCEPT;//截单转寄
        // 	IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_QUERY_DELIVERTM;//时效标准及价格查询
        //  IServiceCodeStandard standardService = ExpressServiceCodeEnum.COM_RECE_CLOUD_PRINT_WAYBILLS;//面单打印
        //  IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_UPLOAD_ROUTE;//路由上传
        //   IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_SEARCH_PROMITM;//预计派送时间查询
        //  IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_EXCE_CHECK_PICKUP_TIME;//揽件服务时间查询
        //  IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_VALIDATE_WAYBILLNO;//运单号合法性校验


        List<OrderInfo> orderInfoList = orderInfoService.getByStatus("2");
        List<String> logististicsIds = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfoList) {
            logististicsIds.add(orderInfo.getLogisticsId());
        }
        List<OrderLogistics> orderLogisticsList = orderLogisticsService.getByIds(logististicsIds);
        List<String> mailNoList = new ArrayList<>();
        String pattern = "^(\\d{12}|SF\\d{13})$";
        for (OrderLogistics orderLogistics : orderLogisticsList) {
            String mailNo = orderLogistics.getLogisticsNo();
            if (mailNo != null && Pattern.matches(pattern, mailNo)) {
                mailNoList.add(mailNo);
            }
        }

        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
//        Double cell = Math.ceil(mailNoList.size() / 10.0);
//        for (int i = 0; i < cell.intValue(); i++) {
//            List<String> list = null;
//            if (mailNoList.size() - i * 10 >= 10) {
//                list = mailNoList.subList(i * 10, (i + 1) * 10);
//            } else {
//                list = mailNoList.subList(i * 10, mailNoList.size());
//            }
        for (OrderLogistics orderLogistics : orderLogisticsList) {
            String mailNo = orderLogistics.getLogisticsNo();
            if (mailNo != null && !Pattern.matches(pattern, mailNo)) {
                continue;
            }
            // set common header
            Map<String, String> params = new HashMap<String, String>();

            String timeStamp = String.valueOf(System.currentTimeMillis());
            String msgData = tools.packageMsgData(standardService);
            RequestMSGData requestMSGData = new RequestMSGData();
            List<String> trackingNumber = new ArrayList<>();
            trackingNumber.add("444003077898");
            trackingNumber.add("441003077850");
            List<String> list = new ArrayList<>();
            list.add(mailNo);
            requestMSGData.setTrackingNumber(list);
            requestMSGData.setCheckPhoneNo(orderLogistics.getTelNum().substring(orderLogistics.getTelNum().length() - 4, orderLogistics.getTelNum().length()));
//        msgData = "{\n" +
//                "\t\"language\": \"zh-CN\",\n" +
//                "\t\"trackingType\": \"1\",\n" +
//                "\t\"trackingNumber\": [\"444003077898\", \"441003077850\"],\n" +
//                "\t\"methodType\": \"1\"\n" +
//                "}";
            msgData = JSONObject.toJSONString(requestMSGData);
            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD_PROD));
//        params.put("trackingType", "1");
//        List<String> list = new ArrayList<>();
//        list.add("SF1389788825591");
//        params.put("trackingNumber",list.toString());
//        params.put("language","zh-CN");
//        params.put("methodType","1");

            // System.out.println(params.get("requestID"));
            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));
            System.out.println("====调用实际请求：" + params);
            String result = HttpClientUtil.post(CALL_URL_PROD, params);

            System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
            System.out.println("===调用地址 ===" + CALL_URL_PROD);
            System.out.println("===顾客编码 ===" + CLIENT_CODE);
            System.out.println("===返回结果：" + result);

            try {
                APIResult apiResult = JSONObject.parseObject(result, APIResult.class);
                if (apiResult != null && apiResult.getApiResultCode().equals("A1000") && apiResult.getApiResultData() != null) {
                    APIResultData apiResultData = JSONObject.parseObject(apiResult.getApiResultData(), APIResultData.class);
                    System.out.println(apiResultData.toString());
                    if (apiResultData.getErrorCode().equals("S0000")) {
                        // Todo 保存数据
                        MSGData msgData1 = apiResultData.getMsgData();
                        List<RouteResps> routeRespsList = msgData1.getRouteResps();
                        for (RouteResps routeResps : routeRespsList) {
                            String mainNo = routeResps.getMailNo();
                            Wrapper queryWrapper = Wrappers.<OrderLogisticsExpressInfo>lambdaQuery()
                                    .eq(OrderLogisticsExpressInfo::getMailNo, mainNo);
                            orderLogisticsExpressInfoService.remove(queryWrapper);
                            List<Routes> routesList = routeResps.getRoutes();
                            for (Routes routes : routesList) {
                                OrderLogisticsExpressInfo info = new OrderLogisticsExpressInfo();
                                info.setMailNo(mainNo);
                                info.setAcceptAddress(routes.getAcceptAddress());
                                info.setOpCode(routes.getOpCode());
                                info.setAcceptTime(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", routes.getAcceptTime()));
                                info.setCreateTime(DateUtils.getNowDate());
                                info.setRemark(routes.getRemark());
                                orderLogisticsExpressInfoService.save(info);
                                OrderLogistics orderLogistics1 = orderLogisticsService.getOne(Wrappers.<OrderLogistics>lambdaQuery().eq(OrderLogistics::getLogisticsNo, mailNo).last("limit 1"));
                                if (routes.getOpCode().equals("50")) {
                                    //揽收
                                    orderLogistics1.setStatus("1");
                                    orderLogisticsService.saveOrUpdate(orderLogistics1);
                                } else if (Integer.parseInt(routes.getOpCode()) >= 30 && Integer.parseInt(routes.getOpCode()) < 40) {
                                    //在途
                                    orderLogistics1.setStatus("1");
                                    orderLogisticsService.saveOrUpdate(orderLogistics1);
                                } else if (routes.getOpCode().equals("204")) {
                                    //派件
                                    orderLogistics1.setStatus("5");
                                    orderLogisticsService.saveOrUpdate(orderLogistics1);

                                } else if (routes.getOpCode().equals("8000")) {
                                    //签收
                                    orderLogistics1.setStatus("3");
                                    orderLogisticsService.saveOrUpdate(orderLogistics1);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
